// axios基础封装
import axios from "axios";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { useUserStore } from "@/stores/user";
import router from "@/router";

const httpInstance = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

// axios请求拦截器
httpInstance.interceptors.request.use(
  (config) => {
    //从pinia获取token
    const userStore = useUserStore();
    //按照后端要求拼接token数据
    if (userStore.userToken) {
      const token = userStore.userToken;
      config.headers.token = `${token}`;
    }
    return config;
  },
  (e) => Promise.reject(e)
);

// axios响应式拦截器
httpInstance.interceptors.response.use(
  (res) => {
    const result = res.data;

    //请求失败
    if (result.code === 0) {
      ElMessage({
        type: "warning",
        message: result.msg,
      });
      return null;
    }

    // //请求成功
    // if (result.code === 1) {
    //   ElMessage({
    //     type: "success",
    //     message: result.msg,
    //   });
    // }

    return result;
  },
  (e) => {
    const userStore = useUserStore();

    //响应结果
    const result = e.response.data;

    //507token失效处理
    if (result.code === 507) {
      ElMessage({
        type: "warning",
        message: result.msg,
      });
      //清除本地用户数据
      userStore.clearUserInfo();

      router.push("/login");

      return Promise.reject(e);
    }

    if (result.code) {
      //统一错误提示
      ElMessage({
        type: "warning",
        message: e.response.data.msg,
      });

      return Promise.reject(e);
    }
  }
);

export default httpInstance;
